import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'
import type { RouteMeta } from '@/types/user'

// 基础静态路由（Layout 先注册，children 动态添加）
const baseRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/LoginIndex.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/register/RegisterIndex.vue')
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/index.vue'),
    redirect: '/home',
    children: []
  }
]

// 所有动态子路由
export const asyncRoutes: RouteRecordRaw[] = [
  {
    path: 'home',
    name: 'Home',
    component: () => import('@/views/home/HomeIndex.vue'),
    meta: { title: '首页', icon: 'House', permission: 'home' }
  },
  {
    path: 'users',
    name: 'User',
    component: () => import('@/views/user/UserIndex.vue'),
    meta: { title: '用户管理', icon: 'User', permission: 'users' }
  },
  {
    path: 'setting',
    name: 'Setting',
    component: () => import('@/views/setting/SettingIndex.vue'),
    meta: { title: '设置', icon: 'Setting', permission: 'system' }
  },
  {
    path: 'profile',
    name: 'Profile',
    component: () => import('@/views/profile/ProfileIndex.vue'),
    meta: { title: '个人信息', icon: 'User', permission: 'profile' }
  },
  {
    path: 'item',
    name: 'Item',
    component: () => import('@/views/item/ItemIndex.vue'),
    meta: { title: '商品管理', icon: 'Goods', permission: 'item' }
  },
  {
    path: 'address',
    name: 'Address',
    component: () => import('@/views/address/AddressIndex.vue'),
    meta: { title: '地址管理', icon: 'Address', permission: 'addresses' }
  },
  {
    path: 'imageGenerator',
    name: 'ImageGenerator',
    component: () => import('@/views/image/ImageGenerator.vue'),
    meta: { title: '图片生成', icon: 'Picture', permission: 'image' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: baseRoutes
})

// 添加动态路由
export function addRoutes(permissions: string[]) {
  const accessRoutes = asyncRoutes.filter(route =>
    permissions.includes(route.meta?.permission as string)
  )

  accessRoutes.forEach(route => {
    router.addRoute('Layout', route)
    console.log(`[动态路由] 添加: /${route.path}`)
  })
}

// 重置路由（保留基础）
export function resetRouter() {
  router.getRoutes().forEach(route => {
    if (
      route.name &&
      !['Login', 'Register', 'Layout'].includes(String(route.name))
    ) {
      router.removeRoute(route.name)
      console.log(`[路由移除] ${String(route.name)}`)
    }
  })
}

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const token = userStore.token

  if (to.path === '/login' || to.path === '/register') {
    if (token) {
      // 已登录用户访问登录页，重定向到首页
      return next('/home')
    }
    return next()
  }

  if (!token) {
    // 未登录用户访问需要权限的页面，重定向到登录页
    userStore.clearUserData()
    resetRouter()
    return next('/login')
  }

  try {
    // 检查是否已经有动态路由
    const hasRoutes = router.getRoutes().some(route =>
      route.name !== 'Layout' &&
      route.name !== 'Login' &&
      route.name !== 'Register'
    )

    if (!hasRoutes) {
      // 如果没有动态路由，重新添加
      if (!userStore.userInfo) {
        await userStore.getUserInfo()
      }
      resetRouter()
      addRoutes(userStore.permissions)
      return next({ ...to, replace: true })
    }

    return next()
  } catch (err) {
    console.error('[导航守卫] 获取用户信息失败:', err)
    userStore.clearUserData()
    resetRouter()
    return next('/login')
  }
})

export default router
